package com.codefish.codefishseckill.config.interceptor;

import com.codefish.codefishseckill.entity.User;
import com.codefish.codefishseckill.exception.GlobalException;
import com.codefish.codefishseckill.service.UserService;
import com.codefish.codefishseckill.utils.CookieUtil;
import com.codefish.codefishseckill.vo.RespBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器 (已弃用，引入了Spring Security来实现认证和授权)
 *
 * @author codefish
 * @version 1.0
 * @date 2022/07/05 下午 05:48
 */
@Deprecated
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie中获取token
        String token = CookieUtil.getValueByKey(request, CookieUtil.USER_INFO_KEY);
        //cookie获取不到，从header获取token
        if (StringUtils.isEmpty(token)) {
            token = request.getHeader(CookieUtil.USER_INFO_KEY);
        }

        if (token == null) {
            throw new GlobalException(RespBeanFactory.denied("用户未登录"));
        }

        User user = userService.getUserByToken(token);
        if (user == null) {
            throw new GlobalException(RespBeanFactory.denied("无效的token"));
        }

        request.getSession().setAttribute("userInfo", user);
        return true;
    }
}
